package com.gomtel.smartdevice.ui.fragment;

import android.graphics.Color;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.gomtel.smartdevice.R;
import com.gomtel.smartdevice.base.WatchBaseFragemnt;
import com.gomtel.smartdevice.global.DataClass;
import com.gomtel.smartdevice.moudle.db.entity.StepCountContentInfo;
import com.gomtel.smartdevice.moudle.event.CommonEvent;
import com.gomtel.smartdevice.utils.ChartUtils;
import com.gomtel.smartdevice.utils.LogUtil;
import com.gomtel.smartdevice.widget.CalenderUtilsClass;
import com.gomtel.smartdevice.widget.MaxDataIntervalClass;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/5/22 0022.
 */

public class PedometerWeekFragemnt extends WatchBaseFragemnt implements View.OnClickListener {

    @BindView(R.id.layout_life)
    ImageButton layout_life;
    @BindView(R.id.layout_right)
    ImageButton layout_right;
    @BindView(R.id.layout_type)
    TextView layout_type;
    @BindView(R.id.chart_bar)
    BarChart chart_bar;
    @BindView(R.id.chart_line)
    LineChart chart_line;

    @BindView(R.id.step_target)
    TextView step_target;
    @BindView(R.id.step_complete)
    TextView step_complete;
    @BindView(R.id.length_target)
    TextView length_target;
    @BindView(R.id.length_complete)
    TextView length_complete;

    private ChartUtils chartUtils;
    private int maxInterval;
    private int line_maxInterval;
    private CalenderUtilsClass calenderUtilsClass;
    private int startPoint = 0;
    private MaxDataIntervalClass maxDataIntervalClass;
    private DataClass dataClass;
    private int[] mDataYs;
    private int[] mDataLine;
    private int week = 0;
    private String currentDay;

    @Override
    protected void registerEvent(CommonEvent commonevent) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_week;
    }

    @Override
    protected void initClass() {
        chartUtils = new ChartUtils();
        dataClass = new DataClass(dataManager);
        calenderUtilsClass = new CalenderUtilsClass();
        maxDataIntervalClass = new MaxDataIntervalClass(dataManager);
    }

    @Override
    protected void initData() {
        currentDay = calenderUtilsClass.getCurrentDay(false);
        mDataYs = dataClass.getStepCountWeekDb();
        mDataLine = dataClass.getPathLengWeekDb();
        for (int i = 0; i <mDataYs.length; i++) {
            LogUtil.e(TAG,"week : " + mDataYs[i]);
        }
    }

    @Override
    protected void initView() {
        layout_type.setText(getString(R.string.current_week));
        chartChangeAction();
        StandardProgress();
    }

    public void chartChangeAction() {
        maxInterval = maxDataIntervalClass.getMaxInterval(mDataYs, DataClass.standardMax);
        line_maxInterval = maxDataIntervalClass.getMaxInterval(mDataLine, DataClass.standardLineMax);
        chartUtils.setBarChart(chart_bar, maxInterval / 2, maxInterval, mDataYs.length);
        loadBarChartData(chart_bar);
        chartUtils.setLineChart(chart_line, line_maxInterval / 2, line_maxInterval, mDataLine.length);
        loadLineChartData(chart_line);
    }

    public void StandardProgress() {
        int currentPathLengthAll = 0;
        int currentStepAll = 0;
        int weekStepAll = 0;
        int weekPathLengAll = 0;
        int[] currentPathDataInts = dataClass.PathLengthBeforeDb(currentDay);
        int[] currentStepInts = dataClass.StepCountBeforeDb(currentDay);
        int[] weekStepAllInts = dataClass.StepCountWeekBeforeDb(getWeek());
        int[] weekPathLengAllInts = dataClass.PathLengthWeekBeforeDb(getWeek());
        for (int i = 0; i < currentPathDataInts.length; i++) {
            currentPathLengthAll = currentPathLengthAll + currentPathDataInts[i];
        }
        for (int i = 0; i < currentStepInts.length; i++) {
            currentStepAll = currentStepAll + currentStepInts[i];
        }
        for (int i = 0; i < weekStepAllInts.length; i++) {
            weekStepAll = weekStepAll + weekStepAllInts[i];
        }
        for (int i = 0; i < weekPathLengAllInts.length; i++) {
            weekPathLengAll = weekPathLengAll + weekPathLengAllInts[i];
        }

        step_target.setText(new StringBuffer().append("平均每天 ").append(Math.round(weekStepAll / 7)));
        step_complete.setText(new StringBuffer().append("今日完成 ").append(currentStepAll).toString());

        length_target.setText(new StringBuffer().append("平均每天 ").append(FormatFloat(Math.round(weekPathLengAll / 7))).append("km").toString());
        length_complete.setText(new StringBuffer().append("今日完成 ").append(FormatFloat(currentPathLengthAll)).append("km").toString());
    }

    private String FormatFloat(int i) {
        DecimalFormat df = new DecimalFormat("0.00");
        String format = df.format((float) i / 1000);
        return format;
    }

    @Override
    protected void initListener() {
        layout_life.setOnClickListener(this);
        layout_right.setOnClickListener(this);
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_life:
                week = week + 1;
                ChangeAction();
                break;
            case R.id.layout_right:
                week = week - 1;
                if (week < 1)
                    week = 0;
                ChangeAction();
                break;
        }
    }

    private String getWeek() {
        String lastTimeInterval = calenderUtilsClass.getLastTimeInterval(week);
        String[] split = lastTimeInterval.split("/");
        String s = split[0];
        return s;
    }

    private void ChangeAction() {
        String lastTimeInterval = calenderUtilsClass.getLastTimeInterval(week);
        String[] split = lastTimeInterval.split("/");
        mDataYs = dataClass.StepCountWeekBeforeDb(split[0]);
        mDataLine = dataClass.PathLengthWeekBeforeDb(split[0]);
        chartChangeAction();
        if (week == 0) {
            layout_type.setText(getString(R.string.current_week));
        } else {
            layout_type.setText(splitText(split));
        }
        StandardProgress();
    }

    private String splitText(String[] split) {
        String s1 = split[0];
        String s2 = split[1];
        String[] split1 = s1.split("-");
        String[] split2 = s2.split("-");
        String s = new StringBuffer().append(indexformat(split1[1])).append(".").append(indexformat(split1[2])).append("~").append(indexformat(split2[2])).toString();
        return s;
    }

    private String indexformat(String text) {
        String value = text;
        if (Integer.valueOf(text) < 10)
            value = new StringBuffer().append(0).append(text).toString();
        return value;
    }

    /**
     * 加载并设置柱形图的数据
     *
     * @param chart
     */
    private void loadBarChartData(BarChart chart) {
        //所有数据点的集合
        ArrayList<BarEntry> entries = new ArrayList<>();
        for (int i = 0; i < mDataYs.length; i++) {
            entries.add(new BarEntry(mDataYs[i], i));
        }
        //柱形数据的集合
        BarDataSet mBarDataSet = new BarDataSet(entries, "");
        int colors[] = {getActivity().getResources().getColor(R.color.blue_style)};
        mBarDataSet.setColors(colors);//设置每条柱子的颜色
        mBarDataSet.setHighLightAlpha(255);//设置点击后高亮颜色透明度
        mBarDataSet.setHighLightColor(Color.TRANSPARENT);
        mBarDataSet.setValueTextColor(Color.TRANSPARENT);
        mBarDataSet.setBarShadowColor(Color.TRANSPARENT);
        //BarData表示挣个柱形图的数据
        BarData mBarData = new BarData(calenderUtilsClass.getLastWeek(week), mBarDataSet);
        chart.setData(mBarData);
        // 设置动画
        chart.animateY(2000);
    }

    /**
     * 为折线图设置数据
     *
     * @param chart
     */
    private void loadLineChartData(final LineChart chart) {
        ArrayList<LineDataSet> allLinesList = new ArrayList<LineDataSet>();
        ArrayList<Entry> entryList = new ArrayList<Entry>();
        for (int i = 0; i < mDataLine.length; i++) {
            //Entry(yValue,xIndex);一个Entry表示一个点，第一个参数为y值，第二个为X轴List的角标
            entryList.add(new Entry(mDataLine[i], i));
        }
        //LineDataSet可以看做是一条线
        LineDataSet dataSet = new LineDataSet(entryList, "dataLine");
        dataSet.setLineWidth(1f);
        dataSet.setCircleSize(2f);// 显示的圆形大小
        dataSet.setDrawValues(false); // 隐藏折线图每个数据点的值
        dataSet.setValueTextColor(Color.GREEN);
        dataSet.setDrawCubic(false);//允许设置平滑曲线
        dataSet.setDrawFilled(true);//是否填充折线下方
        dataSet.setCircleColor(getResources().getColor(R.color.blue_style));
        dataSet.setCircleColorHole(getResources().getColor(R.color.blue_style));
        dataSet.setColor(getResources().getColor(R.color.blue_style));
        dataSet.setFillColor(Color.rgb(76, 219, 255));//折线图下方填充颜色设置
        dataSet.setFillAlpha(100);
        dataSet.setValueTextSize(24f);
        allLinesList.add(dataSet);
        LineData mChartData = new LineData(calenderUtilsClass.getLastWeek(week), allLinesList);
        chart.setData((LineData) mChartData);
        // 设置动画
        chart.setVisibleXRangeMaximum(startPoint + 1);
        chart.setVisibleXRangeMinimum(mDataLine.length - 1);

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint())
            if (toastUtil != null) {
                initData();
                initView();
            }
    }

}
